import { BaseServices } from "./base.services";
import { Uri, Method, RespInfo, config } from "./config";
import { appContext } from "@/models/app.context";
import { AssetInfo } from "@/models/asset";
import { AssetToken } from "../models/asset";

class AssetService extends BaseServices {
  private static _instance: AssetService;
  public static get instance(): AssetService {
    if (this._instance == null) {
      this._instance = new AssetService();
    }
    return this._instance;
  }
  constructor() {
    super();
  }

  /** 增加一个资源 */
  public add(name: string, format: string, md5: string, size: number, hash: string, owner: string, url: string, small?: string, snapshot?: string, width?: number, height?: number, remark?: string): Promise<AssetInfo> {
    const uri = config.usersbeasking + Uri.Asset + Method.Add;
    const data = { name, url, format, hash, width, height, md5, size, owner, small, snapshot, remark };
    return new Promise<AssetInfo>((resolve) => {
      this.request(uri, data).then((res: RespInfo<AssetInfo>) => {
        resolve(res.info);
      });
    });
  }

  /** 获取上传token */
  token() {
    const url = config.usersbeasking + Uri.Asset + Method.Token;
    const data = {};
    return new Promise<void>((resolve) => {
      this.request(url, data, "GET").then((res: RespInfo<AssetToken>) => {
        appContext.setGlobal({ assetToken: res.info });
        resolve();
      });
    });
  }
}

export const assetService: AssetService = AssetService.instance;
